import React from 'react';
import { Editor } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';
import { useTranslation } from 'react-i18next';
import { message } from 'antd';
import 'bytemd/dist/index.css';
import 'highlight.js/styles/vs.css';

interface MarkdownEditorProps {
  value?: string;
  onChange?: (value: string) => void;
}

export const MarkdownEditor: React.FC<MarkdownEditorProps> = ({ value = '', onChange }) => {
  const { t } = useTranslation();

  const plugins = [
    gfm(),
    highlight(),
  ];

  return (
    <Editor
      value={value}
      plugins={plugins}
      onChange={onChange}
      uploadImages={async (files) => {
        try {
          const file = files[0];
          if (file.size > 2 * 1024 * 1024) {
            message.error(t('upload.maxSize'));
            return [];
          }

          if (!['image/jpeg', 'image/png'].includes(file.type)) {
            message.error(t('upload.format'));
            return [];
          }

          const formData = new FormData();
          formData.append('file', file);

          const response = await fetch('/api/upload', {
            method: 'POST',
            body: formData
          });

          if (!response.ok) {
            throw new Error(t('upload.error'));
          }

          const data = await response.json();
          message.success(t('upload.success'));

          return [{
            url: data.url,
            alt: file.name,
            title: file.name
          }];
        } catch (error) {
          message.error(t('upload.error'));
          return [];
        }
      }}
    />
  );
};
